package cn.bdqn.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//与数据库连接的工具类
public class DBUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //静态代码块加载配置文件，获取连接数据库的参数
    static {
        Properties p = new Properties();
        //通过类加载器读文件为字节流
        InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            p.load(is);
            driver = p.getProperty("driver");
            url = p.getProperty("url");
            username = p.getProperty("username");
            password = p.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //与数据库连接的三个对象
    public Connection conn;
    public PreparedStatement pstm;
    public ResultSet rs;

    //获取连接
    public Connection getConn() {
        try {
            Class.forName(driver);//加载驱动
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    //关闭所有资源
    public void closeAll(Connection conn, PreparedStatement pstm, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (pstm != null) pstm.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //增删改公用的操作
    public int updateAll(String sql, Object... os) {
        int count = 0;
        try {
            pstm = getConn().prepareStatement(sql);
            if (os != null && os.length > 0) {
                for (int i = 0; i < os.length; i++) {
                    pstm.setObject(i + 1, os[i]);
                }
            }
            count = pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, pstm, null);
        }
        return count;
    }

}
